package kr.co.graviti.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import java.util.Calendar;
import java.util.GregorianCalendar;

import org.apache.struts.upload.FormFile;

import kr.co.graviti.common.vo.MultipartUpLoadFileInfoVO;

public class FilePolicyUtil {
	
	/** 첨부파일 리네임 
	 * @param f
	 * @return
	 * @throws Exception
	 */
	public File rename(File f,String row) throws Exception {  //File f는 원본 파일
		//if (createNewFile(f)) return f; //생성된 f가
		//확장자가 없는 파일 일때 처리
		String name = f.getName();
		String body = new FilePolicyUtil().newReName(name,row);
		f = new File(f.getParent(), body);
	    return f;
	}

	/*
	private boolean createNewFile(File f) { 
		try {
			return f.createNewFile();  //존재하는 파일이 아니면
		}catch (IOException ignored) {
			return false;
		}
	}
	*/
	
	/**
	 * @param filename	: 첨부파일명 
	 * @param gubun		: rename 구분자명 
	 * @return
	 * @throws Exception
	 */
	public String newReName(String filename,String row) throws Exception{
		
		String rename = "",ext = "";
		int dot = filename.lastIndexOf(".");
		if(dot != -1) ext = filename.substring(dot);
	
		StringBuffer sn	= new StringBuffer();
		Calendar c = new GregorianCalendar();
		sn.append(String.valueOf(c.get(Calendar.YEAR)));
		sn.append(c.get(Calendar.MONTH)+1);
		sn.append(c.get(Calendar.HOUR_OF_DAY));
		sn.append(c.get(Calendar.MINUTE));
		sn.append(c.get(Calendar.SECOND));
		sn.append(c.get(Calendar.MILLISECOND));
		
		rename = row+"_"+sn.toString()+ext;
		rename = rename.trim();
		sn.setLength(0);
		
		return rename;
	}
	
	
	/** 디렉토리 생성 
	 * @param path
	 * @throws Exception
	 */
	public void mkdir(String path) throws Exception{
		File dir = new File(path);
		if(!dir.exists()) dir.mkdirs();
	}
	
	public MultipartUpLoadFileInfoVO multiFileUpLoad(FormFile theFile,String board_type,String filePath,int count) throws Exception {
		
		MultipartUpLoadFileInfoVO multi = new MultipartUpLoadFileInfoVO();
		
		// 업로드 폴더 생성 
		new FilePolicyUtil().mkdir(filePath + board_type);
		String fileUploadPath = filePath + board_type+"/";
		String orginalFilename = theFile.getFileName();
		if(!orginalFilename.equals("")){
			int filesize = theFile.getFileSize();
			try{
				InputStream stream = theFile.getInputStream();
				String saveFilename = new FilePolicyUtil().newReName(orginalFilename,"file"+Integer.toString(count));
				File file = new File(fileUploadPath,saveFilename);
				
				OutputStream bos = new FileOutputStream(file);
				int bytesRead = 0;
				byte[] buffer = new byte[filesize];
				while ((bytesRead = stream.read(buffer, 0, filesize)) != -1) {
					bos.write(buffer, 0, bytesRead);
				}
				bos.close();
				stream.close();
				
				multi.setContentType(CommonUtil.fileext(orginalFilename)); // 첨부파일 확장자
				multi.setFilesize( Long.parseLong(Integer.toString(filesize)) );
				multi.setOrginalFilename(orginalFilename);
				multi.setSaveFilename(saveFilename);
				multi.setUploadPath(fileUploadPath);
				
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		
		return multi;
	}
	
	/** 
	 * 이미지 파일  검사 
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public boolean checkImgExt(String filename) throws Exception{
		
		boolean result = false;
		String ext = "";
		int dot = filename.lastIndexOf(".");
		if(dot != -1){
			ext	= filename.substring(dot);
			ext = ext.toLowerCase();
			
			System.out.println("======>"+ext);
			String str[] = new String[5];
			str[0] = ".gif";
			str[1] = ".jpg";
			str[2] = ".jpeg";
			str[3] = ".png";
			str[4] = ".bmp";
			
			ext = ext.trim();
			for(int i=0;i<str.length;i++){
				if(ext.equals(str[i])){
					result = true;
					break;
				}
			}
		}else{
			result = false;
		}
		return result;
	}
	
	/** 
	 * 확장자 검사 
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public boolean checkFilExt(String filename) throws Exception{
		
		boolean result = true;
		String ext = "";
		
		int dot = filename.lastIndexOf(".");
		
		if(dot != -1){
			ext	= filename.substring(dot);
			ext = ext.toLowerCase();
			String str[] = new String[23];
			
			str[0] = ".php";
			str[1] = ".php3";
			str[2] = ".php5";
			str[3] = ".phtml";
			str[4] = ".asp";
			str[5] = ".aspx";
			str[6] = ".ascx";
			str[7] = ".jsp";
			str[8] = ".cfm";
			str[9] = ".cfc";
			str[10] = ".pl";
			str[11] = ".bat";
			str[12] = ".exe";
			str[13] = ".dll";
			str[14] = ".reg";
			str[15] = ".cgi";
			str[16] = ".html";
			str[17] = ".htm";
			str[18] = ".js";
			str[19] = ".sh";
			str[20] = ".com";
			str[21] = ".class";
			str[22] = ".java";
			
			ext = ext.trim();
			for(int i=0;i<str.length;i++){
				if(ext.equals(str[i])){
					result = false;
					break;
				}
			}
			
		}else{
			result = true;
		}
		
		return result;
	}
}
